<template>
  <div class="app-container">
    <el-card :bordered="false">
      <el-form ref="formValidate" :rules="ruleValidate" :model="formValidate" label-width="130px">
        <el-row :gutter="24">
          <!-- 商品信息-->
          <el-col>
            <el-form-item label="商品名称：" prop="goodName">
              <el-input v-model="formValidate.goodName" placeholder="请输入商品名称"/>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="商品分类：" prop="categoryId">
              <el-select v-model="formValidate.categoryId">
                <el-option v-for="item in categoryList" :disabled="item.isVisible === 0"
                           :value="item.categoryId" :key="item.categoryId" :label="item.categoryName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="商品关键字：" prop="keywords">
              <el-input v-model="formValidate.keywords" placeholder="请输入商品关键字,多个关键字用英文逗号隔开"/>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="商品简介：" prop="">
              <el-input v-model="formValidate.description" type="textarea" :rows="3" placeholder="请输入商品简介"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品封面图：" prop="showImage">
              <picture-manager
                width="150"
                height="150"
                :value="formValidate.showImage"
              >
              </picture-manager>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品轮播图：" prop="detailImages">
              <picture-manager :pic-num="5" width="150" height="150" :value="formValidate.detailImages">
              </picture-manager>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品规格：" props="specType">
              <el-radio-group v-model="formValidate.specType">
                <el-radio :label="0" class="radio">单规格</el-radio>
                <el-radio :label="1">多规格</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="attrs.length!==0&&formValidate.specType === 1">
              <div v-for="(item, index) in attrs" :key="index">
                <div class="acea-row row-middle"><span class="mr5">{{ item.value }}</span>
                  <i class="el-icon-circle-close" @click="handleRemoveAttr(index)"></i>
                </div>
                <div class="rulesBox">
                  <el-tag type="dot" closable color="primary" v-for="(j, indexn) in item.detail" :key="indexn" :name="j"
                          class="mr20" @close="handleRemoveAttrVal(item.detail,indexn)"
                  >{{ j }}
                  </el-tag>
                  <el-input placeholder="请输入属性名称" v-model="item.detail.attrsVal"
                            style="width: 200px"
                  >
                    <el-button slot="append" type="primary" @click="createAttr(item.detail.attrsVal,index)">添加
                    </el-button>
                  </el-input>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="showAddAttrBtn">
            <el-form-item>
              <el-button type="primary" icon="md-add" @click="showBtn=false" class="mr15">添加规格</el-button>
              <el-button type="success" @click="generate">立即生成</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="showAddAttrInput">
            <el-col :xl="6" :lg="9" :md="10" :sm="24" :xs="24">
              <el-form-item label="规格：">
                <el-input placeholder="请输入规格" v-model="formDynamic.attrsName"/>
              </el-form-item>
            </el-col>
            <el-col :xl="6" :lg="9" :md="10" :sm="24" :xs="24">
              <el-form-item label="规格值：">
                <el-input v-model="formDynamic.attrsVal" placeholder="请输入规格值"/>
              </el-form-item>
            </el-col>
            <el-col :xl="6" :lg="5" :md="10" :sm="24" :xs="24">
              <el-button type="primary" @click="createAttrName">确定</el-button>
              <el-button type="danger" @click="showBtn=true">取消</el-button>
            </el-col>
          </el-col>
          <el-form ref="formMany" :model="many" :rules="ruleValidate">
            <!-- 多规格设置-->
            <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24" align="center"
                    v-if="formValidate.specType === 1&&many.manyFormValidate.length && header.length!==0 && attrs.length!==0"
            >
              <!-- 多规格表格-->
              <el-table :data="many.manyFormValidate" size="small" style="width: 90%;">
                <el-table-column v-for="(item,index) in header" :key="index" :label="item.title" :property="item.slot"
                                 align="center"
                >
                  <template align="center" slot-scope="scope">
                    <div v-if="scope.column.property == 'pic'" align="center">
                      <single-pic v-model="scope.row[scope.column.property]" type="image" :num="1" :width="60"
                                  :height="60"
                      />
                    </div>
                    <div v-else-if="scope.column.property.indexOf('value') != -1" align="center">
                      {{ scope.row[scope.column.property] }}
                    </div>
                    <div v-else-if="scope.column.property == 'action'" align="center">
                      <a @click="delAttrTable(scope.$index)" align="center">删除</a>
                    </div>
                    <div v-else align="center">
                      <el-form-item
                        :rules="ruleValidate[scope.column.property]"
                        :prop="'manyFormValidate.' + scope.$index + '.'+scope.column.property"
                      >
                        <el-input v-model.number="scope.row[scope.column.property]"/>
                      </el-form-item>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-form>
          <el-form ref="formOne" :model="oneFormValidate[0]" :rules="ruleValidate">
            <!-- 单规格-->
            <el-col :xl="23" :lg="24" :md="24" :sm="24" :xs="24" align="center" v-if="formValidate.specType === 0">
              <el-table :data="oneFormValidate" size="small" style="width: 90%;">
                <el-table-column label="原价" align="center">
                  <template slot-scope="scope">
                    <el-form-item prop="price">
                      <el-input type="text" v-model.number="scope.row.price"/>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="折扣价" align="center">
                  <template slot-scope="scope">
                    <el-form-item prop="costPrice">
                      <el-input type="text" v-model.number="scope.row.costPrice"/>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="库存" align="center">
                  <template slot-scope="scope">
                    <el-form-item prop="stock">
                      <el-input type="text" v-model.number="scope.row.stock"/>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-form>

          <!--          <el-col :span="24">
                      <el-form-item label="开启积分兑换：" props="point_buy">
                        <el-radio-group v-model="formValidate.point_buy">
                          <el-radio :label="0" class="radio">不开启</el-radio>
                          <el-radio :label="1">开启</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>-->

        </el-row>
        <br/>
        <el-row>
          <el-col :span="10">
            <el-form-item label="购买返回积分：">
              <el-input-number v-model="formValidate.point" :min="0" placeholder="请输入积分"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="排序：">
              <el-input-number :min="0" v-model="formValidate.sort" placeholder="请输入排序"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" class="submission" @click="onSubmit('formValidate')">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import PictureManager from '@/components/ImageUpload/PictureManager'
import * as categoryApi from '@/api/shop/category.js'
import * as goodsApi from '@/api/shop/goods'


export default {
  name: 'GoodsAdd',
  components: {
    PictureManager
  },
  data() {
    let checkStock = (rule, value, callback) => {
      if (value != 0 && !value) {
        return callback(new Error('此项为必填项'))
      }
      if (!Number.isInteger(value)) {
        callback(new Error('请输入数字值'))
      } else {
        if (value <= 0) {
          callback(new Error('数量必须大于0'))
        } else {
          callback()
        }
      }
    }
    return {
      formValidate: {
        showImage: [],
        detailImages: [],
        specType: 0,
        point: 0,
        sort: 0,
        point_buy: 0,
        description: ''
      },
      header: []
      ,
      // 单规格表格data
      oneFormValidate: [
        {}
      ],
      // 添加规格数据
      formDynamic: {
        attrsName: '',
        attrsVal: ''
      },
      //已经添加的规格数据
      attrs: []
      ,
      //商品信息校验
      ruleValidate: {
        goodName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择商品名称', trigger: 'change' }
        ],
        keywords: [
          { required: true, message: '请输入关键字', trigger: 'blur' }
        ],
        showImage: [
          { required: true, message: '图片必选', trigger: 'blur' }
        ],
        detailImages: [
          { required: true, message: '图片必选', trigger: 'blur' }
        ],
        price: [
          { required: true, validator: checkStock, trigger: 'blur' }
        ]
        ,
        costPrice: [
          { required: true, validator: checkStock, trigger: 'blur' }
        ],
        stock: [
          { required: true, validator: checkStock, trigger: 'blur' }
        ]
      },
      categoryList: {},
      //是否显示添加规格和立即生成按钮
      showBtn: true,
      many: {
        manyFormValidate: []
      }
    }
  }
  ,
  computed: {
    showAddAttrInput() {
      return !this.showBtn && this.formValidate.specType === 1
    },
    showAddAttrBtn() {
      return this.showBtn && this.formValidate.specType === 1
    }
  },
  created() {
    if (typeof (this.$route.query.goodId) === 'string') {
      goodsApi.goodsList({ goodId: this.$route.query.goodId }).then((res) => {
        this.formValidate = Object.assign({}, res.rows[0], { showImage: [res.rows[0].showImage] })
        if (this.formValidate.specType == 0) {
          //单规格
          this.oneFormValidate =[JSON.parse(this.formValidate.ysGoodsSku).data[0]];
          console.log(this.oneFormValidate);
        } else {
          this.many.manyFormValidate = Object.assign([], JSON.parse(this.formValidate.ysGoodsSku).data)
          this.header = Object.assign([], JSON.parse(this.formValidate.ysGoodsSku).head)
          this.attrs = Object.assign([], JSON.parse(this.formValidate.ysGoodsSku).attrs)
        }
      })
    }
    categoryApi.categoryList().then((res) => {
      this.categoryList = res.rows
    })
  },
  methods: {
    clearAttr() {
      this.formDynamic.attrsName = ''
      this.formDynamic.attrsVal = ''
    },
    createAttrName() {
      if (this.formDynamic.attrsName && this.formDynamic.attrsVal) {
        let data = {
          value: this.formDynamic.attrsName,
          detail: [
            this.formDynamic.attrsVal
          ]
        }
        this.attrs.push(data)
        let hash = {}
        this.attrs = this.attrs.reduce(function(item, next) {
          hash[next.value] ? '' : hash[next.value] = true && item.push(next)
          return item
        }, [])
        this.clearAttr()
        this.showBtn = true
        this.many.manyFormValidate.length > 0 && this.generate()
      } else {
        this.$message.warning('请添加完整的规格！')
      }
    },
    // 添加属性
    createAttr(num, idx) {
      if (num) {
        this.attrs[idx].detail.push(num)
        var hash = {}
        this.attrs[idx].detail = this.attrs[idx].detail.reduce(function(item, next) {
          hash[next] ? '' : hash[next] = true && item.push(next)
          return item
        }, [])
        this.many.manyFormValidate.length > 0 && this.generate()
      } else {
        this.$message.warning('请添加属性！')
      }
    },
    // 删除规格
    handleRemoveAttr(index) {
      this.attrs.splice(index, 1)
      this.many.manyFormValidate.length > 0 && this.generate()
    },
    // 删除属性
    handleRemoveAttrVal(item, index) {
      item.splice(index, 1)
      this.mmany.anyFormValidate.length > 0 && this.generate()
    },
    // 立即生成
    generate() {
      if (this.attrs.length == 0) {
        return
      }
      //生成表格头属性
      this.header = [
        { title: '原价', slot: 'price' },
        { title: '折扣价', slot: 'costPrice' },
        { title: '库存', slot: 'stock' },
        { title: '操作', slot: 'action' }
      ]
      let head = this.attrs.reduce((acc, cur, index) => {
        acc.push({ title: cur.value, slot: 'value' + (index + 1) })
        return acc
      }, [])
      this.header = head.concat(this.header)
      //把规格值组装成一个数组,用来生成规格组合
      let arrs = this.attrs.reduce((acc, cur, index) => {
        acc.push(cur.detail)
        return acc
      }, [])
      /**
       * 思路: 以第一项为基础,循环合并之后的每一项再循环的值
       * @param {*} acc 累计的值
       * @param {*} cur 当前遍历项
       * @param {*} index 当前遍历索引
       * @return result 生成的组合
       */
      let result = arrs.reduce((acc, cur, index) => {
        // 从第二项开始合并值
        if (index > 0) {
          let saveArr = []
          acc.forEach(item => {
            cur.forEach(subItem => {
              saveArr.push(`${item},${subItem}`)
            })
          })
          acc = saveArr
        }
        return acc
      }, arrs[0])
      //根据生成的组合,组装出来每种组合的对象数组[{value1:*,value2:*....},{value1:*,value2:*....}...]
      let data = result.reduce((accc, cur, index) => {
        let obj = {}
        cur.split(',').forEach((item, iindex) => {
          obj['value' + (iindex + 1)] = item
        })
        accc.push(obj)
        return accc
      }, new Array())
      this.many.manyFormValidate = data
    },
    // 删除表格中的属性
    delAttrTable(index) {
      this.many.manyFormValidate.splice(index, 1)
    },
    onSubmit() {
      let that=this;
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          this.$refs['formMany'].validate((valid) => {
            if (valid) {
              let object
              if (this.formValidate.specType === 1) {
                //重组一下数据
                let data=this.many.manyFormValidate.map(function(item) {
                  let attrStr="";
                  for(let i=1;i<=that.attrs.length;i++){
                    attrStr+=item["value"+i]+",";
                  }
                  item['attr']=attrStr.substr(0,attrStr.length-1);
                  return item;
                })
                object = { head: this.header, attrs: this.attrs, data }
              } else {
                object = { head: this.header, data: this.oneFormValidate }
              }
              let jsonStr = JSON.stringify(object)
              let sj = Object.assign({}, this.formValidate, { ysGoodsSku: jsonStr })
              sj.showImage = sj.showImage[0]
              goodsApi.updateOrSave(sj).then((res) => {
                // 调用全局挂载的方法
                this.$store.dispatch('tagsView/delView', this.$route)
                // 返回上一步路由
                this.$router.go(-1)
              })
            } else {
              return false
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
td {
  margin-top: 10px;
}
</style>
